import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:kq_flutter_core_widget/utils/toast_util.dart';
import 'package:kq_flutter_core_widget/utils/get_not_route.dart';
import 'package:kq_flutter_tv_widgets/widgets/button/kq_small_button.dart';
import 'package:kq_flutter_tv_widgets/widgets/splitView/split_view.dart';

///一体机导航框架demo
class GetNotRouteDemo extends StatefulWidget {
  const GetNotRouteDemo({super.key});

  @override
  State<StatefulWidget> createState() => GetNotRouteDemoState();
}

class GetNotRouteDemoState extends State<GetNotRouteDemo> {
  final SplitViewController controller = SplitViewController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SplitView(
        controller: controller,
        parent: ParentView(controller),
      ),
    );
  }
}

class ParentView extends StatelessWidget {
  final SplitViewController controller;
  final Random random = Random();

  ParentView(this.controller, {super.key});

  @override
  Widget build(BuildContext context) {
    return KqSmallButton(
      title: "点击",
      onTap: (d) {
        controller.open(GetNotRoute().toPage(
          ///tips：这里不能加const，加了const则不会重建。
          ChildView(),
          arguments: {"test": "我执行了Build:${random.nextInt(1000)}"},
        ).call());
      },
    );
  }
}

class ChildView extends StatefulWidget implements LifeCycle {
  const ChildView({super.key});

  @override
  State<StatefulWidget> createState() => ChildViewState();

  @override
  void recycle() {
    ///需要移除上一个Controller，才会再次走Controller的[onInit]方法
    Get.delete<ChildController>();
  }
}

class ChildViewState extends State<ChildView> {
  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      KqToast.showNormal("第一次我执行了initState");
    });
    super.initState();
  }

  @override
  void didUpdateWidget(covariant ChildView oldWidget) {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      KqToast.showNormal("再次点击我执行了didUpdateWidget");
    });
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    final controller = Get.put(ChildController());
    return GetBuilder<ChildController>(
      init: controller,
      builder: ((controller) {
        return Text(controller.test);
      }),

      ///这个必须的加，当调用了[Get.delete]重新创建Controller后必须调用该方法刷新controller
      didUpdateWidget: (old, state) {
        state.controller = controller;
        state.controller?.addListener(state.getUpdate);
      },
    );
  }
}

class ChildController extends GetxController {
  String test = "123";

  @override
  void onInit() {
    super.onInit();
    test = GetNotRoute().getArgOrParams("test") ?? "000";

    WidgetsBinding.instance.addPostFrameCallback((_) {
      KqToast.showNormal("我执行了onInit");
    });

    request();
  }

  request() {
    Future.delayed(const Duration(seconds: 5), () {
      test = "我是网络模拟数据";
      update();
    });
  }
}
